package com.rt.cms.controller;

import com.rt.cms.common.Constants;
import com.rt.cms.common.base.Result;
import com.rt.cms.common.utils.SendMessageUtil;
import com.rt.cms.controller.base.BaseController;
import com.rt.cms.data.entity.CompanyInfoBean;
import com.rt.cms.data.entity.TbApprovalRecord;
import com.rt.cms.data.entity.TbCompanyInfo;
import com.rt.cms.data.entity.TbCompayUploadInfo;
import com.rt.cms.data.entity.system.User;
import com.rt.cms.service.CompanyInfoService;
import com.rt.cms.service.system.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;


@Controller
@RequestMapping("/company")
public class CompanyInfoController extends BaseController {

    @Autowired
    private CompanyInfoService companyInfoService;
    @Autowired
    private UserService userService;

    @RequestMapping(method = RequestMethod.GET)
    public String addCompanyInfo(HttpServletRequest request, ModelMap map2) {
        return "archives/addCompanyInfo";
    }


    /**
     * 新增企业信息
     */
    @RequestMapping(value = "/saveCompanyInfo")
    @ResponseBody
    public Map<String, Object> saveCompanyInfo(HttpServletRequest request, ModelMap model, TbCompanyInfo tbCompanyInfo) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("status", "1");
        /*if (!checkInputValue(tbCompanyInfo, map)) {
            return map;
        }*/
        //校验用户是否已注册
        List<TbCompanyInfo> tbCompanyInfos = companyInfoService.getCompanyInfoByBusinessCode(tbCompanyInfo.getBusinessCode());
        if (tbCompanyInfos.size() > 0) {
            map.put("message", "此证件号已存在");
            return map;
        }
        Date now = new Date();
        User user = (User) request.getAttribute(Constants.CURRENT_USER);
        if (tbCompanyInfo.getInputTime() == null) {
            tbCompanyInfo.setInputTime(now);
        }
        tbCompanyInfo.setOperateId(user.getId().intValue());
        tbCompanyInfo.setStatus(Constants.Due_Diligence);
        tbCompanyInfo.setDormant(Constants.unDormancy);

        TbApprovalRecord tbApprovalRecord = new TbApprovalRecord();
        tbApprovalRecord.setOperateId(user.getId().intValue());
        tbApprovalRecord.setOperateTime(now);
        tbApprovalRecord.setOperateType(Constants.Add);
        tbApprovalRecord.setStatus(Constants.Due_Diligence);
        int id = companyInfoService.saveCompanyInfo(tbCompanyInfo, tbApprovalRecord);
        if (id > 0) {
            map.put("status", "0");
            map.put("message", "新增信息成功");
        } else {
            map.put("message", "新增信息失败");
        }
        map.put("id", id);
        return map;
    }


    /**
     * 修改企业信息
     */
    @RequestMapping(value = "/editCompanyInfo")
    @ResponseBody
    public Result editCompanyInfo(HttpServletRequest request, TbCompanyInfo tbCompanyInfo) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("status", "1");
        /*if (!checkInputValue(tbCompanyInfo, map)) {
            return map;
        }*/
        TbCompanyInfo tbCompanyInfo1 = companyInfoService.getCompanyInfoById(tbCompanyInfo.getId());
        //校验用户是否已注册
        List<TbCompanyInfo> tbCompanyInfos = companyInfoService.getCompanyInfoByBusinessCode(tbCompanyInfo.getBusinessCode());
        if (tbCompanyInfos.size() > 0) {
            if (null != tbCompanyInfo.getBusinessCode() && null != tbCompanyInfo1.getBusinessCode() && !tbCompanyInfo1.getBusinessCode().equals(tbCompanyInfo.getBusinessCode())) {
                //map.put("message", "此证件号已注册");
                return Result.Failure("1", "此证件号已存在");
            }
        }
        //查询记录当前状态
        TbCompanyInfo tbCompanyInfoNew = companyInfoService.getCompanyInfoById(tbCompanyInfo.getId());
        /*if (tbCompanyInfoNew.getStatus() > 1) {
            return Result.Failure("001", "当前状态不能审核！");
        }*/

        User user = (User) request.getAttribute(Constants.CURRENT_USER);
        Date now = new Date();
        TbApprovalRecord tbApprovalRecord = new TbApprovalRecord();
        tbApprovalRecord.setOperateId(user.getId().intValue());
        tbApprovalRecord.setOperateTime(now);
        tbApprovalRecord.setOperateType(Constants.Modify);
        tbApprovalRecord.setStatus(Constants.Due_Diligence);

        //修改基本企业信息
        if (companyInfoService.editCompanyBasicInfo(tbCompanyInfo, tbApprovalRecord) > 0) {
            return Result.Success();
        } else {
            return Result.Failure("405", "操作失败！");
        }
    }

    /**
     * 新增图片信息
     */
    @RequestMapping(value = "/saveCompanyUploadInfo")
    @ResponseBody
    public Result saveCompanyUploadInfo(HttpServletRequest request, String id, String operateType) throws ServletException, IOException {
        if (null == operateType || "".equals(operateType)) {
            operateType = String.valueOf(Constants.Add);
        }else if(String.valueOf(Constants.upLoadReport).equals(operateType)){
            CompanyInfoBean tbCompayUploadInfo = companyInfoService.getCompanyInfoBeanById(Integer.valueOf(id));
            if(tbCompayUploadInfo.getTbCompayUploadInfos().size()==0){
                return Result.Failure("406","请先上传企业图片信息");
            }
        }
        return uploadImage(request, id, operateType);
    }

    /**
     * 企业担保修改图片信息
     */
    @RequestMapping(value = "/editCompanyUploadInfo")
    @ResponseBody
    public Result editCompanyUploadInfo(HttpServletRequest request, TbCompanyInfo tbCompanyInfo) throws ServletException, IOException {

        String operateType = String.valueOf(Constants.Modify);
        String id = String.valueOf(tbCompanyInfo.getUploadId());
        //查询企业id
        //TbCompayUploadInfo tbCompayUploadInfo = companyInfoService.getCompanyUploadInfoById(tbCompanyInfo.getUploadId());
        //TbCompanyInfo tbCompanyInfoNew = companyInfoService.getCompanyInfoById(tbCompayUploadInfo.getComInfoId());
        /*if (tbCompanyInfoNew.getStatus() > 1) {
            return Result.Failure("001", "当前状态不能审核！");
        }*/
        return uploadImage(request, id, operateType);
    }

    public Result uploadImage(HttpServletRequest request, String id, String operateType) throws ServletException, IOException {
        Map<String, Object> map = new HashMap<String, Object>();
        TbCompayUploadInfo tbCompayUploadInfo = null;
        if (null != operateType && Constants.Modify == Integer.valueOf(operateType)) {
            tbCompayUploadInfo = companyInfoService.getCompanyUploadInfoById(Integer.valueOf(id));
            id = String.valueOf(tbCompayUploadInfo.getComInfoId());
        }

        String message = "";
        /*ShiroHttpServletRequest shiroRequest = (ShiroHttpServletRequest) request;*/
        CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver();
        MultipartHttpServletRequest multipartRequest = commonsMultipartResolver.resolveMultipart(request);
        //MultipartHttpServletRequest multipartRequest = commonsMultipartResolver.resolveMultipart((HttpServletRequest)request.getRequest);

        Iterator iter = multipartRequest.getFileMap().values().iterator();
        while (iter.hasNext()) {
            String oname = "";
            MultipartFile file = (MultipartFile) iter.next();
            String labelName = file.getName();
            if (!"".equals(file.getOriginalFilename())) {
                String curfilekzmstr = "";
                if (file.getOriginalFilename().lastIndexOf(".") > -1) {
                    curfilekzmstr = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."), file.getOriginalFilename().length());
                }
                oname = (int) ((Math.random() * 9 + 1) * 100000) + "" + (int) ((Math.random() * 9 + 1) * 100000) + curfilekzmstr;
                String outpath = Constants.realUrl + oname;
                File newfile = new File(outpath);
                if (!newfile.getParentFile().exists()) {                //判断有没有父路径，就是判断文件整个路径是否存在
                    newfile.getParentFile().mkdirs();                //不存在就全部创建
                }
                FileOutputStream fos = new FileOutputStream(outpath);
                fos.write(file.getBytes());
                fos.close();
            }
            oname = Constants.showUrl + oname;
            if (null != operateType && Constants.Modify == Integer.valueOf(operateType)) {
                message = saveFiles(id, tbCompayUploadInfo.getPicName(), oname, operateType, tbCompayUploadInfo);
            } else {
                message = saveFiles(id, labelName, oname, operateType, tbCompayUploadInfo);
            }
        }
        if (null != operateType && Constants.Add == Integer.valueOf(operateType)) {
            Map requestMap = request.getParameterMap();
            Set keSet = requestMap.entrySet();
            for (Iterator itr = keSet.iterator(); itr.hasNext(); ) {
                Map.Entry me = (Map.Entry) itr.next();
                String key = me.getKey().toString(); //获取参数名
                String labelName = java.net.URLDecoder.decode(java.net.URLDecoder.decode(key, "UTF-8"), "UTF-8");
                if (!"id".equals(labelName)) {
                    message = saveFiles(id, labelName, "", operateType, tbCompayUploadInfo);
                }
            }
        }
        //HashMap nullMap= ((DefaultMultipartHttpServletRequest) multipartRequest).getMultipart() ;

        //Map<String, String> map1 = multipartRequest.getMultipartParameterContentTypes();
        map.put("message", message);
        return Result.Success();

    }


    private String saveFiles(String id, String labelName, String oname, String operateType, TbCompayUploadInfo tbCompayUploadInfo1) {
        //文件存储
        String message = "";
        TbCompayUploadInfo tbCompayUploadInfo = new TbCompayUploadInfo();
        tbCompayUploadInfo.setComInfoId(Integer.valueOf(id));
        tbCompayUploadInfo.setPicUrl(oname);
        tbCompayUploadInfo.setIsDisplay(Constants.Display);
        if (labelName.contains("用户新增")) {
            tbCompayUploadInfo.setIsDefined(Constants.Defined);
            labelName = labelName.substring(4);
        } else {
            tbCompayUploadInfo.setIsDefined(Constants.UnDefined);
        }

        if (null != operateType && Constants.Modify == Integer.valueOf(operateType)) {
            if (null != tbCompayUploadInfo1 && tbCompayUploadInfo1.getIsDefined() == 1) {
                tbCompayUploadInfo.setIsDefined(Constants.Defined);
            }
        }
        tbCompayUploadInfo.setPicName(labelName);
        if (companyInfoService.saveCompanyUploadInfo(tbCompayUploadInfo) > 0) {
            message = "文件上传成功";
            if (null != operateType && Constants.upLoadReport == Integer.valueOf(operateType)) {
                //更改记录状态
                TbCompanyInfo tbCompanyInfo = companyInfoService.getCompanyInfoById(Integer.valueOf(id));
                tbCompanyInfo.setStatus(Constants.Audit_Of_Department);

                TbApprovalRecord tbApprovalRecord = new TbApprovalRecord();
                tbApprovalRecord.setStatus(Constants.Audit_Of_Department);
                tbApprovalRecord.setOperateType(Constants.upLoadReport);
                tbApprovalRecord.setDemo("");
                tbApprovalRecord.setComInfoId(Integer.valueOf(id));
                tbApprovalRecord.setOperateTime(new Date());
                companyInfoService.editCompanyInfo(tbCompanyInfo, tbApprovalRecord);

                // 给B用户发短信
                // 此时可能B角从未操作过，因此不能在tb_company_info中取，只能在sys_user中取pid
                String phone = userService.queryParentPhoneById(tbCompanyInfo.getOperateId());
                SendMessageUtil.postUrl(Constants.Sms_DueDiligence2DepartmentAudit, Constants.Sms_URL, phone);
            } else if (null != operateType && Constants.Modify == Integer.valueOf(operateType)) {
                //原图片隐藏
                tbCompayUploadInfo1.setIsDisplay(Constants.unDisplay);
                companyInfoService.editCompanyUploadInfo(tbCompayUploadInfo1);
                message = "文件上传成功";
            } else {
                message = "文件上传失败";
            }

        } else {
            message = "文件上传失败";
        }
        return message;
    }


    private boolean checkInputValue(TbCompanyInfo tbCompanyInfo, Map map) {
        if (null == tbCompanyInfo.getBusinessCode() || "".equals(tbCompanyInfo.getBusinessCode())) {
            map.put("message", "营业执照编号不能为空");
            return false;
        }
        if (null == tbCompanyInfo.getComName() || "".equals(tbCompanyInfo.getComName())) {
            map.put("message", "企业名称不能为空");
            return false;
        }
        if (1 == tbCompanyInfo.getComType() && (null == tbCompanyInfo.getBusinessCode() || "".equals(tbCompanyInfo.getBusinessCode()))) {
            map.put("message", "授信期限不能为空");
            return false;
        }
        if (1 == tbCompanyInfo.getComType() && (null == tbCompanyInfo.getBusinessCode() || "".equals(tbCompanyInfo.getBusinessCode()))) {
            map.put("message", "授信额度不能为空");
            return false;
        }
        return true;
    }


    /**
     * 企业其它图片修改名称=
     */
    @RequestMapping(value = "/updateCompanyUploadInfo")
    @ResponseBody
    public Result updateCompanyUploadInfo(TbCompayUploadInfo tbCompayUploadInfo) throws ServletException, IOException {

        try {
            tbCompayUploadInfo.setIsDefined(1);
            tbCompayUploadInfo.setIsDisplay(1);
            companyInfoService.editCompanyUploadInfo(tbCompayUploadInfo);
            return Result.Success();
        } catch (Exception e) {
            return Result.Failure("2002", "操作异常");
        }
    }

    /*public static void main(String[] args){
        String s ="用户新增测试";
        System.out.println(s.substring(4));
    }*/

}
